package com.totem.base.filter;

import com.totem.base.filter.support.CachedRequestWrapper;
import com.totem.base.util.FilterUtil;
import com.totem.base.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

@Slf4j
public class DataReusableFilter extends OncePerRequestFilter {
    private static final AntPathMatcher ignoresMatch = new AntPathMatcher();
    private Set<String> ignores = Set.of(
            "/admin/config/system"
    );

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        CachedRequestWrapper cachedRequestWrapper = new CachedRequestWrapper(request);
        ContentCachingResponseWrapper cachingResponseWrapper = new ContentCachingResponseWrapper(response);

        try {
            filterChain.doFilter(cachedRequestWrapper, cachingResponseWrapper);

            // cachingResponseWrapper.setHeader("Access-Control-Allow-Origin", "*");
            /*
            cachingResponseWrapper.setHeader("Access-Control-Allow-Methods", "*");
            cachingResponseWrapper.setHeader("Access-Control-Allow-Headers", "*");
            cachingResponseWrapper.setHeader("Access-Control-Max-Age", "3600");
             */
        } finally {
            cachingResponseWrapper.copyBodyToResponse();
        }
    }
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        if(FilterUtil.ignoreMethod(request)) return true;

        final String requestUri = RequestUtil.getRelativePath(request);
        return ignores.stream().anyMatch(e->ignoresMatch.match(e, requestUri));
    }
}
